import { download } from '@/apis/file'
import { useAnnotationStore } from '@/stores/annotation'
import { MessagePlugin } from 'tdesign-vue-next'
import { nextTick, ref, watch, Ref, onMounted, onBeforeUnmount } from 'vue'
import { getSelection } from '@notjosh/rangy-core'

const annotationStore = useAnnotationStore()

function useHtmlLoader(frameRef: Ref<HTMLIFrameElement>) {
  const zoom = ref(1)
  const zoomIn = () => {
    zoom.value = Math.min(zoom.value + 0.1, 3.0)
  }
  const zoomOut = () => {
    zoom.value = Math.max(zoom.value - 0.1, 0.2)
  }

  watch(zoom, () => {
    frameRef.value?.contentDocument?.documentElement.style.setProperty(
      'zoom',
      zoom.value + ''
    )
  })

  const loading = ref(false)
  const loadProgress = ref(0)
  const loadHtml = (
    fileId: Ref<string>,
    checkTest: () => boolean,
    nextTickCb: Function
  ) => {
    if (checkTest()) {
      const fileReader = new FileReader()
      fileReader.onload = (e) => {
        frameRef.value.contentDocument!.documentElement.innerHTML = e.target!
          .result as string
        // 自动调整文本zoom大小
        zoom.value = (frameRef.value.clientWidth || 600) / 600
        loading.value = false
        nextTick(() => nextTickCb())
      }
      fileReader.onerror = () => {
        MessagePlugin.error('文件读取失败')
        loading.value = false
      }
      if (!window.FileReader) {
        MessagePlugin.error('您的浏览器版本过低，请升级')
      }
      const doDownload = () => {
        if (frameRef.value && fileId.value) {
          loadProgress.value = 0
          loading.value = true
          download(fileId.value, (p) => {
            loadProgress.value = p
          })
            .then((res) => {
              fileReader.readAsText(res)
            })
            .catch(() => {
              loading.value = false
            })
        }
      }
      doDownload()
      watch(fileId, () => {
        doDownload()
      })
    }
  }

  // 监听事件，划选文本后，同步到annotaionStore
  const copyCurrentWord = () => {
    annotationStore.currentLabel.content = getSelection(
      frameRef.value.contentWindow!
    ).toString()
  }
  onMounted(() => {
    frameRef.value.contentWindow?.addEventListener('mousemove', copyCurrentWord)
    frameRef.value.contentWindow?.addEventListener('click', copyCurrentWord)
  })
  onBeforeUnmount(() => {
    frameRef.value.contentWindow?.removeEventListener(
      'mousemove',
      copyCurrentWord
    )
    frameRef.value.contentWindow?.removeEventListener('click', copyCurrentWord)
  })

  // 监听scrollmark，滚动定位到文本
  watch(
    () => annotationStore.scrollBookmark,
    () => {
      if (annotationStore.scrollBookmark) {
        getSelection(frameRef.value.contentWindow!).moveToBookmark(
          annotationStore.scrollBookmark
        )
        let node = getSelection(frameRef.value.contentWindow!).anchorNode
        if (node && node.nodeType != 1) {
          node = node.parentElement
        }
        const element = node as HTMLElement
        element.scrollIntoView({ behavior: 'smooth', block: 'center' })
        getSelection(frameRef.value.contentWindow!).removeAllRanges()
      }
      annotationStore.currentLabel.content = ''
    }
  )

  return {
    zoomIn,
    zoomOut,
    loadHtml,
    loading,
    loadProgress,
  }
}

export { useHtmlLoader }
